import * as API from '@/services';
import {
  KfBackendEnumPicker,
  DEFAULT_FORM_LAYOUT,
  KfBizQuickFormProps,
  KfFloatingContextProps,
  KfInput,
  KfQuickForm,
  KfTextArea,
  KfMenuPicker,
} from 'kf-web-library';
import { Form } from 'antd';
import React, { FunctionComponent } from 'react';

const FormItem = Form.Item;
type QueryEntity = API.Role;
type CreateEntity = API.Role_Create;
type ModifyEntity = API.Role_Modify;

type DataFormProps = {} & KfBizQuickFormProps & KfFloatingContextProps;

/**
 * 角色表单
 */
const QuickForm: FunctionComponent<DataFormProps> = (props) => {
  const { formType, bizId, ...rest } = props;

  return (
    <KfQuickForm
      formType={formType}
      formProps={{
        ...DEFAULT_FORM_LAYOUT,
      }}
      defaultQueryRequest={() =>
        API.queryRole(bizId!).then((resp) => {
          if (resp.flag) {
            resp.data = {
              ...resp.data,
              permIds: resp.data.perms?.map((p) => p.id) || [],
              menuIds: resp.data.menus?.map((m) => m.id) || [],
            } as ModifyEntity;
          }
          return new Promise((resolve) => resolve(resp));
        })
      }
      submitRequest={{
        create: (formValues) => API.createRole({ ...formValues } as CreateEntity),
        modify: (formValues) => API.modifyRole({ ...formValues, id: bizId } as ModifyEntity),
      }}
      {...rest}
    >
      <FormItem name={nameof<ModifyEntity>((x) => x.name)} label="角色名称" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.code)} label="角色编码" rules={[{ required: true }]}>
        <KfInput />
      </FormItem>
      <FormItem name={nameof<ModifyEntity>((x) => x.menuIds)} label="菜单权限" rules={[{ required: false }]}>
        <KfMenuPicker.TreeSelect treeSelect={{ treeCheckable: true, treeCheckStrictly: true, maxTagCount: 10 }} />
      </FormItem>
      {/*<FormItem name={nameof<ModifyEntity>((x) => x.permIds)} label="数据权限" rules={[{required: false}]}>
                <KfPermPicker mode="multiple" maxTagCount={99}/>
            </FormItem>*/}
      <FormItem name={nameof<ModifyEntity>((x) => x.description)} label="备注" rules={[{ required: false }]}>
        <KfTextArea />
      </FormItem>
    </KfQuickForm>
  );
};

export default QuickForm;
